//
//  PhotoBrowserViewCell.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/6/23.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
import SDWebImage
protocol PhotoBrowserViewCellDelegate:NSObjectProtocol {
    func iamgeViewClickForCell(cell:PhotoBrowserViewCell)
}
class PhotoBrowserViewCell: UICollectionViewCell {
//    代理属性
    var delegate : PhotoBrowserViewCellDelegate?
//     MARK:- 属性设置
     var picURL : NSURL?{
        didSet{
            guard let picURL = picURL else{
                return
            }
            setupUIContent(picURL)
        }
    }
//    MARK:- 懒加载属性
    private lazy var scrllollView : UIScrollView = UIScrollView()
     lazy var imageView : UIImageView = UIImageView()
    private lazy var photoBrowserProgressView : PhotoBrowserProgressView = PhotoBrowserProgressView()
    //MARK:- 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
}
//MARK:- UI设置相关
extension PhotoBrowserViewCell{
    func setupUI() {
//        添加子控件
        contentView.addSubview(scrllollView)
        scrllollView.addSubview(imageView)
        contentView.addSubview(photoBrowserProgressView)
//        设置frame
        scrllollView.frame = contentView.bounds
        scrllollView.frame.size.width -= 15
        photoBrowserProgressView.backgroundColor = UIColor.clearColor()
        photoBrowserProgressView.bounds = CGRect(x: 0, y: 0, width: 60, height: 60)
        photoBrowserProgressView.center = CGPoint(x: contentView.bounds.width * 0.5, y: contentView.bounds.height * 0.5)
//        设置属性
        photoBrowserProgressView.hidden = true
//        设置图片放大缩小的比例
        scrllollView.minimumZoomScale = 0.5
        scrllollView.maximumZoomScale = 2
        scrllollView.delegate = self
//        给imageView添加手势
        imageView.userInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(PhotoBrowserViewCell.imageViewClick))
        imageView.addGestureRecognizer(tap)
    }
}
//    MARK:事件监听
extension PhotoBrowserViewCell{
   @objc private func imageViewClick() {
    delegate?.iamgeViewClickForCell(self)
    }
}
//MARK:- 设置imageView的frame
extension PhotoBrowserViewCell{
    func setupUIContent(picURL:NSURL) {
//        屏幕的宽和高
        let screenH = UIScreen.mainScreen().bounds.height
        let screenW = UIScreen.mainScreen().bounds.width
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromMemoryCacheForKey(picURL.absoluteString) else{
            return
        }
        let imageViewH = screenW/image.size.width * image.size.height
        imageView.frame = CGRect(x: 0, y: 0, width: screenW, height: imageViewH)
//        判断是否需要设置内边距
        if imageViewH < screenH {
            let topInset = (screenH - imageViewH) * 0.5
            scrllollView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0)
        }else{
            scrllollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
//        展示图片
        imageView.image = image
//        设置scrlloView的内容尺寸
        scrllollView.contentSize = CGSize(width: screenW, height: imageViewH)
//        先获取大图URL
        let middlePicURL = changeURLWithSmallPicURl(picURL)
//        下载大图
        imageView.sd_setImageWithURL(middlePicURL, placeholderImage: image, options: [], progress: { (current, total) in
            self.photoBrowserProgressView.hidden = false
            self.photoBrowserProgressView.progress = CGFloat(current) / CGFloat(total)
            }) { (_, _, _, _) in
                self.photoBrowserProgressView.hidden = true
        }
        
    }
}
//MARK:- 小图URL转为大图URL
extension PhotoBrowserViewCell{
    func changeURLWithSmallPicURl(smallPicURL:NSURL) -> NSURL {
        let changePlace = "thumbnail"
        let middlePicURL = (smallPicURL.absoluteString as NSString).stringByReplacingOccurrencesOfString(changePlace, withString: "bmiddle")
        return NSURL(string: middlePicURL)!
    }
}
//MARK:- 遵守协议，实现代理方法
extension PhotoBrowserViewCell : UIScrollViewDelegate{
//    返回的View可以拉伸
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
//    拉伸时调用
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        // 1.设置垂直方向
        var insetV = (UIScreen.mainScreen().bounds.height - view!.frame.height) * 0.5
        insetV = insetV < 0 ? 0 : insetV
        // 2.设置水平方向
        var insetH = (UIScreen.mainScreen().bounds.width - view!.frame.width) * 0.5
        insetH = insetH < 0 ? 0 : insetH
        // 3.设置内边距
        scrollView.contentInset = UIEdgeInsets(top: insetV, left: insetH, bottom: insetV, right: insetH)

    }
}
